package com.itheima.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class SecurityService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        //假设 现在从数据库查询密码了，查出来 密码为 admin
        String password = getUserPassword(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        if ("admin".equals(username)) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            authorities.add(new SimpleGrantedAuthority("delete"));
        }
        if ("zhangsan".equals(username)){
            authorities.add(new SimpleGrantedAuthority("add"));
        }
        return new User(username,new BCryptPasswordEncoder().encode(password),authorities);
    }

    private String getUserPassword(String username) {
        if (username.equals("zhangsan")){
            return "123456";
        }
        return "admin";
    }
}
